package com.medicine.hbp.ui;

import org.kymjs.kjframe.http.HttpParams;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.medicine.hbp.base.BaseActivity;
import com.medicine.hbp.dialog.Loading;
import com.medicine.hbp.http.AppHttpCallBack;
import com.medicine.hbp.http.AppHttps;
import com.medicine.hbp.http.HttpInterface;
import com.medicine.hbp.pay.zfb.PayResult;
import com.medicine.hbp.sp.LoginSp;
import com.medicine.hbp.uitl.StartIntent;
import com.medicine.hbp.R;

/**
 *
 * @author wanghua
 *
 */
public class BannerWebActivity extends BaseActivity {

	private String name = "", url = "";
	private WebView webView;
	private Loading loading;
	private static final int SDK_PAY_FLAG = 1;
	private int type;//1、从Splash进入

	@SuppressLint("NewApi") @Override
	protected void onCreate(Bundle savedactivityState) {
		super.onCreate(savedactivityState);
		type=getIntent().getIntExtra("type", 0);
		setContentView(R.layout.banner_home_act);
		initTop();

		webView = (WebView) findViewById(R.id.webView_act);
		webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
		});
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				loading.dismissDialog();
			}
		});
		WebSettings settings = webView.getSettings();
		settings.setDomStorageEnabled(true);
		settings.setJavaScriptEnabled(true);
		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		settings.setAllowFileAccess(true);// 设置允许访问文件数据
		// settings.setSupportZoom(true);
		// settings.setBuiltInZoomControls(true);
		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		settings.setDatabaseEnabled(true);

		webView.getSettings().setJavaScriptEnabled(true);
		webView.addJavascriptInterface(new JavaScriptInterface(), "obj");
		webView.setWebChromeClient(new WebChromeClient());
		loading = new Loading(aty);
		loading.showDialog();
		url = getIntent().getStringExtra("URL");
		webView.loadUrl(url);
		Log.e("", url);
	}

	class JavaScriptInterface {
		@JavascriptInterface
		public void JavaScriptPayZfb(String subject, String body, String price) {
			httpZfb(subject, body, price);
		}
		@JavascriptInterface
		public void JavaScriptPayZfb(String goodsId, String orderId) {
			if(TextUtils.isEmpty(LoginSp.getToken(aty))){
				StartIntent.startLogin(aty);
			}else{
				httpZfb02(goodsId,orderId);
			}
		}
		@JavascriptInterface
		public void JavaScriptMoreIntg(){
			Intent intent=new Intent(aty,IntegralActivity.class);
			startActivity(intent);
		}
		@JavascriptInterface
		public void JavaScriptIsLogin() {
			StartIntent.startLogin(aty);
		}
	}
	private void initTop() {
		name = getIntent().getStringExtra("NAME");
		TopView topview = (TopView) findViewById(R.id.topview);
		topview.setTitle(name);
		topview.setLeftVisibility(View.GONE);
		topview.setLeftVisibilityExit(View.VISIBLE);
		topview.setRightVisibility(View.INVISIBLE);
		topview.setLeftOnClickExit(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(type==1){
					Intent intent = new Intent(aty, MainActivity.class);
					startActivity(intent);
					finish();
				}else{
					finish();
				}
			}
		});
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case SDK_PAY_FLAG: {
					PayResult payResult = new PayResult((String) msg.obj);
					/**
					 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
					 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
					 * docType=1) 建议商户依赖异步通知
					 */
					String resultInfo = payResult.getResult();// 同步返回需要验证的信息

					String resultStatus = payResult.getResultStatus();
					// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
					if (TextUtils.equals(resultStatus, "9000")) {
						Toast.makeText(BannerWebActivity.this, "支付成功",
								Toast.LENGTH_SHORT).show();
					} else {
						// 判断resultStatus 为非"9000"则代表可能支付失败
						// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
						if (TextUtils.equals(resultStatus, "8000")) {
							Toast.makeText(BannerWebActivity.this, "支付结果确认中",
									Toast.LENGTH_SHORT).show();

						} else {
							// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
							Toast.makeText(BannerWebActivity.this,
									"支付失败" + resultStatus + "-" + resultInfo,
									Toast.LENGTH_SHORT).show();

						}
					}
					break;
				}
				default:
					break;
			}
		}

		;
	};

	private void httpZfb(String subject, String body, String price) {
		HttpParams params = new HttpParams();
		// params.put("partner", PARTNER);// 签约合作者身份ID
		// params.put("seller_id", SELLER); // 签约卖家支付宝账号
		// params.put("out_trade_no", getOutTradeNo() );// 商户网站唯一订单号
		params.put("subject", subject);// 商品名称
		params.put("body", body);// 商品详情
		params.put("price", price);// 商品金额
		// params.put("notify_url", "http://notify.msp.hk/notify.htm");//
		// 服务器异步通知页面路径
		// params.put("service", "mobile.securitypay.pay");// 服务接口名称， 固定值
		// params.put("_input_charset", "utf-8");// 参数编码， 固定值
		// params.put("payment_type", "1"); // 支付类型， 固定值
		// params.put("it_b_pay", "30m");// 设置未付款交易的超时时间
		// params.put("return_url", "m.alipay.com");//
		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		AppHttps.HttpPost(this,HttpInterface.FINDS_SIGN_ZFB, params,
				new AppHttpCallBack<Object>(Object.class, aty) {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						String pay = t.replace("{'key':'", "");
						pay = pay.replace("'}", "");
						ZfbRunnable(pay);
					}

					@Override
					public void onSuccess(Object result) {
					}

					@Override
					public void onFailures(int errorCode, String errorMsg) {
					}
				});
	}
	private void httpZfb02(String goodsId, String orderId) {
		HttpParams params = new HttpParams();
		params.put("goodsId", goodsId);// 商品详情
		params.put("orderId", orderId);// 商品金额
		AppHttps.HttpPost(this,HttpInterface.CONFIRM_ORDER, params,
				new AppHttpCallBack<Object>(Object.class, aty) {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						String pay = t.replace("{'key':'", "");
						pay = pay.replace("'}", "");
						ZfbRunnable(pay);
					}

					@Override
					public void onSuccess(Object result) {
					}

					@Override
					public void onFailures(int errorCode, String errorMsg) {
					}
				});
	}

	/**
	 *
	 * @param payInfo签名参数
	 */
	public void ZfbRunnable(final String payInfo) {
		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(BannerWebActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo, true);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				if(type==1){
					Intent intent = new Intent(aty, MainActivity.class);
					startActivity(intent);
					finish();
				}else{
					finish();
				}
				break;
		}
		return super.onKeyDown(keyCode, event);
	}
}
